package com.diandian.backend.product.service;

import com.diandian.backend.product.constants.DianDianProductConstant;
import com.diandian.backend.product.resp.*;
import com.diandian.base.boot.starter.exception.DefaultException;
import com.diandian.base.boot.starter.response.PageResult;
import com.diandian.backend.product.domain.ProductOfflineInfo;
import com.diandian.backend.product.dto.*;
import com.diandian.backend.product.mapper.ProductOfflineInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class ProductOfflineInfoService {

    @Autowired
    private ProductOfflineInfoMapper productOfflineInfoMapper;

    @Autowired
    private ProductOfflineInfoSkuService productOfflineInfoSkuService;

    @Autowired
    private ProductOfflineInfoPictureVideoService productOfflineInfoPictureVideoService;

    @Autowired
    private ProductOfflineCategoryTreeService productOfflineCategoryTreeService;

    @Autowired
    private ProductOfflineBrandTreeService productOfflineBrandTreeService;

    public PageResult page(ProductOfflineInfoPageParamDTO requestDTO){

        requestDTO.check();
        int pageNum = requestDTO.getPageNum();
        int pageSize = requestDTO.getPageSize();

        // 查询总数
        int totalCount = productOfflineInfoMapper.getCount(requestDTO);

        // 查询数据集合
        List<ProductOfflineInfo> dataList = productOfflineInfoMapper.getPage(requestDTO, requestDTO.getPageSize(), (requestDTO.getPageNum() - 1) * requestDTO.getPageSize());

        // 组装数据
        List<ProductOfflineInfoPageResp> respList = new ArrayList<>();
        if(dataList != null && dataList.size() > 0){

            // 获取所有品牌和分类
            Map<String, String> categoryMap = getCategoryCodeAndNameMap(requestDTO.getBelong());
            Map<String, String> brandMap = getBrandCodeAndNameMap(requestDTO.getBelong());

            dataList.stream().forEach( x ->{
                ProductOfflineInfoPageResp item = new ProductOfflineInfoPageResp();
                item.setId(x.getId());
                item.setBelong(x.getBelong());
                item.setSkuCount(x.getSkuCount() == null ? 0 : x.getSkuCount());
                item.setCode(x.getCode());
                item.setName(x.getName());
                item.setDescription(x.getDescription());
                item.setCategoryCode(x.getCategoryCode());
                if(x.getCategoryCode() != null && !"".equals(x.getCategoryCode())){
                    item.setCategoryName(categoryMap.get(x.getCategoryCode()));
                }
                item.setBrandCode(x.getBrandCode());
                if(x.getBrandCode() != null && !"".equals(x.getBrandCode())){
                    item.setBrandName(brandMap.get(x.getBrandCode()));
                }
                item.setRecommend(x.getRecommend());
                item.setOriginType(x.getOriginType());
                item.setOriginName(x.getOriginName());
                item.setPacking(x.getPacking());
                item.setSaleType(x.getSaleType());
                item.setSellPoint(x.getSellPoint());
                item.setReturnWithoutReason(x.getReturnWithoutReason());
                item.setReturnWithoutReasonDays(x.getReturnWithoutReasonDays());
                item.setSaveWay(x.getSaveWay());
                item.setModel(x.getModel());
                item.setPrice(x.getPrice());
                item.setUpc(x.getUpc());
                item.setUpcImage(x.getUpcImage());
                item.setColor(x.getColor());
                item.setShelvesCode(x.getShelvesCode());
                item.setWeight(x.getWeight());
                item.setWeightUnit(x.getWeightUnit());
                item.setLength(x.getLength());
                item.setWidth(x.getWidth());
                item.setHeight(x.getHeight());
                item.setQualityGuaranteePeriod(x.getQualityGuaranteePeriod());
                item.setQualityGuaranteePeriodUnit(x.getQualityGuaranteePeriodUnit());
                item.setOnShelvesStatus(x.getOnShelvesStatus());
                item.setUseScope(x.getUseScope());
                item.setExtend(x.getExtend());
                item.setCreateUserId(x.getCreateUserId());
                item.setCreateUesrName(x.getCreateUesrName());
                item.setCreateTime(x.getCreateTime());
                item.setUpdateUserId(x.getUpdateUserId());
                item.setUpdateUserName(x.getUpdateUserName());
                item.setUpdateTime(x.getUpdateTime());
                item.setDel(x.getDel());
             respList.add(item);
            });
        }

        return new PageResult(pageNum, pageSize, totalCount, respList);
    }

    private Map<String, String> getCategoryCodeAndNameMap(String belong){
        ProductOfflineCategoryTreeListParamDTO categoryTreeListParamDTO = new ProductOfflineCategoryTreeListParamDTO();
        categoryTreeListParamDTO.setBelongEql(belong);
        List<ProductOfflineCategoryTreeListResp> tempList = productOfflineCategoryTreeService.getList(categoryTreeListParamDTO);
        if(tempList == null || tempList.size() == 0){
            return new HashMap<>();
        }

        return tempList.stream().collect(Collectors.toMap(x -> x.getNodeCode(), x -> x.getNodeName()));
    }

    private Map<String, String> getBrandCodeAndNameMap(String belong){
        ProductOfflineBrandTreeListParamDTO categoryTreeListParamDTO = new ProductOfflineBrandTreeListParamDTO();
        categoryTreeListParamDTO.setBelongEql(belong);
        List<ProductOfflineBrandTreeListResp> tempList = productOfflineBrandTreeService.getList(categoryTreeListParamDTO);
        if(tempList == null || tempList.size() == 0){
            return new HashMap<>();
        }

        return tempList.stream().collect(Collectors.toMap(x -> x.getNodeCode(), x -> x.getNodeName()));
    }

    public List<ProductOfflineInfoListResp> getList(ProductOfflineInfoListParamDTO requestDTO){

        // 查询数据集合
        List<ProductOfflineInfo> dataList = productOfflineInfoMapper.getList(requestDTO);

        // 组装数据
        List<ProductOfflineInfoListResp> respList = new ArrayList<>();
        if(dataList != null && dataList.size() > 0){
            dataList.stream().forEach( x ->{
                ProductOfflineInfoListResp item = new ProductOfflineInfoListResp();
                item.setId(x.getId());
                item.setCode(x.getCode());
                item.setName(x.getName());
                item.setDescription(x.getDescription());
                item.setCategoryCode(x.getCategoryCode());
                item.setBrandCode(x.getBrandCode());
                item.setRecommend(x.getRecommend());
                item.setOriginType(x.getOriginType());
                item.setOriginName(x.getOriginName());
                item.setPacking(x.getPacking());
                item.setSaleType(x.getSaleType());
                item.setSellPoint(x.getSellPoint());
                item.setReturnWithoutReason(x.getReturnWithoutReason());
                item.setReturnWithoutReasonDays(x.getReturnWithoutReasonDays());
                item.setSaveWay(x.getSaveWay());
                item.setModel(x.getModel());
                item.setPrice(x.getPrice());
                item.setUpc(x.getUpc());
                item.setUpcImage(x.getUpcImage());
                item.setColor(x.getColor());
                item.setShelvesCode(x.getShelvesCode());
                item.setWeight(x.getWeight());
                item.setWeightUnit(x.getWeightUnit());
                item.setLength(x.getLength());
                item.setWidth(x.getWidth());
                item.setHeight(x.getHeight());
                item.setQualityGuaranteePeriod(x.getQualityGuaranteePeriod());
                item.setQualityGuaranteePeriodUnit(x.getQualityGuaranteePeriodUnit());
                item.setOnShelvesStatus(x.getOnShelvesStatus());
                item.setUseScope(x.getUseScope());
                item.setExtend(x.getExtend());
                item.setCreateUserId(x.getCreateUserId());
                item.setCreateUesrName(x.getCreateUesrName());
                item.setCreateTime(x.getCreateTime());
                item.setUpdateUserId(x.getUpdateUserId());
                item.setUpdateUserName(x.getUpdateUserName());
                item.setUpdateTime(x.getUpdateTime());
                item.setDel(x.getDel());
                respList.add(item);
            });
        }

        return respList;
    }

    public ProductOfflineInfoDetailResp getDetail(ProductOfflineInfoDetailParamDTO param) {

        ProductOfflineInfo dbData = productOfflineInfoMapper.getDetail(param);
        if(dbData == null){
            return null;
        }

        ProductOfflineInfoDetailResp result = new ProductOfflineInfoDetailResp();
        result.setId(dbData.getId());
        result.setBelong(dbData.getBelong());
        result.setSkuCount(dbData.getSkuCount() == null ? 0 : dbData.getSkuCount());
        result.setCode(dbData.getCode());
        result.setName(dbData.getName());
        result.setDescription(dbData.getDescription());
        result.setCategoryCode(dbData.getCategoryCode());
        result.setBrandCode(dbData.getBrandCode());
        result.setRecommend(dbData.getRecommend());
        result.setOriginType(dbData.getOriginType());
        result.setOriginName(dbData.getOriginName());
        result.setPacking(dbData.getPacking());
        result.setSaleType(dbData.getSaleType());
        result.setSellPoint(dbData.getSellPoint());
        result.setReturnWithoutReason(dbData.getReturnWithoutReason());
        result.setReturnWithoutReasonDays(dbData.getReturnWithoutReasonDays());
        result.setSaveWay(dbData.getSaveWay());
        result.setModel(dbData.getModel());
        result.setPrice(dbData.getPrice());
        result.setUpc(dbData.getUpc());
        result.setUpcImage(dbData.getUpcImage());
        result.setColor(dbData.getColor());
        result.setShelvesCode(dbData.getShelvesCode());
        result.setWeight(dbData.getWeight());
        result.setWeightUnit(dbData.getWeightUnit());
        result.setLength(dbData.getLength());
        result.setWidth(dbData.getWidth());
        result.setHeight(dbData.getHeight());
        result.setQualityGuaranteePeriod(dbData.getQualityGuaranteePeriod());
        result.setQualityGuaranteePeriodUnit(dbData.getQualityGuaranteePeriodUnit());
        result.setOnShelvesStatus(dbData.getOnShelvesStatus());
        result.setUseScope(dbData.getUseScope());
        result.setExtend(dbData.getExtend());
        result.setCreateUserId(dbData.getCreateUserId());
        result.setCreateUesrName(dbData.getCreateUesrName());
        result.setCreateTime(dbData.getCreateTime());
        result.setUpdateUserId(dbData.getUpdateUserId());
        result.setUpdateUserName(dbData.getUpdateUserName());
        result.setUpdateTime(dbData.getUpdateTime());
        result.setDel(dbData.getDel());
        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    public void updateById(ProductOfflineInfoUpdateByIdParamDTO param) {

        param.check();
        String belong = param.getBelong();

        ProductOfflineInfoDetailParamDTO queryDetailDTO = new ProductOfflineInfoDetailParamDTO();
        queryDetailDTO.setId(param.getId());
        queryDetailDTO.setBelong(belong);
        ProductOfflineInfo dbData = productOfflineInfoMapper.getDetail(queryDetailDTO);
        if(dbData == null){
            throw new DefaultException("更新的记录不存在");
        }
        String productCode = dbData.getCode();

        // 判断code重复
        ProductOfflineInfoDetailParamDTO queryNewCodeDetailDTO = new ProductOfflineInfoDetailParamDTO();
        queryNewCodeDetailDTO.setCode(param.getCode());
        queryNewCodeDetailDTO.setBelong(belong);
        ProductOfflineInfo newCodeData = productOfflineInfoMapper.getDetail(queryNewCodeDetailDTO);
        if(newCodeData != null && Long.compare(newCodeData.getId(), param.getId()) != 0){
            throw new DefaultException("已存在此商品编码");
        }

        // 更新基础数据
        param.setUpdateTime(new Date());
        productOfflineInfoMapper.updateById(param);

        // file：先删后增
        productOfflineInfoPictureVideoService.deleteByProductCode(belong, productCode);
        if(param.getFileList() != null && param.getFileList().size() > 0){
            productOfflineInfoPictureVideoService.batchAdd(param.getFileList());
        }

        // sku：先删后增
        productOfflineInfoSkuService.deleteByProductCode(belong, productCode);
        if(param.getSkuList() != null && param.getSkuList().size() > 0){
            productOfflineInfoSkuService.batchAdd(param.getSkuList());
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void deleteById(Long id, String belong) {

        if(id == null){
            throw new DefaultException("数据id不能为空");
        }
        if(belong == null || "".equals(belong)){
            throw new DefaultException("归属标识不能为空");
        }

        ProductOfflineInfoDetailParamDTO queryDetailDTO = new ProductOfflineInfoDetailParamDTO();
        queryDetailDTO.setId(id);
        queryDetailDTO.setBelong(belong);
        ProductOfflineInfoDetailResp detailResp = getDetail(queryDetailDTO);
        if(detailResp == null){
            throw new DefaultException("要删除的商品不存在");
        }
        String productCode = detailResp.getCode();

        // 删除商品基本信息
        productOfflineInfoMapper.deleteById(detailResp.getId());

        // 删除sku
        productOfflineInfoSkuService.deleteByProductCode(belong, productCode);

        // 删除商品下的图片和视频
        productOfflineInfoPictureVideoService.deleteByProductCode(belong, productCode);
    }

    @Transactional(rollbackFor = Exception.class)
    public void deleteByProductCode(String code, String belong) {

        if(code == null || "".equals(code)){
            throw new DefaultException("商品编码不能为空");
        }
        if(belong == null || "".equals(belong)){
            throw new DefaultException("归属标识不能为空");
        }

        ProductOfflineInfoDetailParamDTO queryDetailDTO = new ProductOfflineInfoDetailParamDTO();
        queryDetailDTO.setCode(code);
        queryDetailDTO.setBelong(belong);
        ProductOfflineInfoDetailResp detailResp = getDetail(queryDetailDTO);
        if(detailResp == null){
            throw new DefaultException("要删除的商品不存在");
        }
        String productCode = detailResp.getCode();

        // 删除商品基本信息
        productOfflineInfoMapper.deleteById(detailResp.getId());

        // 删除sku
        productOfflineInfoSkuService.deleteByProductCode(belong, productCode);

        // 删除商品下的图片和视频
        productOfflineInfoPictureVideoService.deleteByProductCode(belong, productCode);
    }

    @Transactional(rollbackFor = Exception.class)
    public void add(ProductOfflineInfoAddParamDTO param) {

        param.check();
        String productCode = param.getCode();
        String belong = param.getBelong();

        // 校验是否存在：商品编码
        ProductOfflineInfoDetailParamDTO queryDetailDTO = new ProductOfflineInfoDetailParamDTO();
        queryDetailDTO.setCode(productCode);
        queryDetailDTO.setBelong(belong);
        ProductOfflineInfoDetailResp detailResp = getDetail(queryDetailDTO);
        if(detailResp != null){
            throw new DefaultException("已存在此商品编码");
        }

        // 保存基础数据
        param.setDel(0);
        if(param.getCreateTime() == null){
            param.setCreateTime(new Date());
        }
        productOfflineInfoMapper.add(param);

        // 保存sku数据
        if(param.getSkuList() != null && param.getSkuList().size() > 0){
            productOfflineInfoSkuService.batchAdd(param.getSkuList());
        }

        // 保存文件数据
        if(param.getFileList() != null && param.getFileList().size() > 0){
            productOfflineInfoPictureVideoService.batchAdd(param.getFileList());
        }
    }
}
